<template>
  <div class="knowledge-container"  v-loading="loading">
    <el-card>
      <template #header>
        <div class="header">
          <span>知识库列表</span>
          <el-button type="primary" @click="handleAdd">添加知识库</el-button>
        </div>
      </template>

      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="code" label="唯一键" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="embeddingStoreId" label="向量库ID" />
        <el-table-column prop="embeddingModelId" label="向量模型ID" />
        <el-table-column prop="descr" label="描述" />
        <el-table-column prop="ctime" label="创建时间" />
        <el-table-column prop="utime" label="更新时间" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
        <!-- 分页 -->
        <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

   

    <!-- 添加/编辑知识库对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="唯一键" prop="code">
          <el-input v-model="form.code" placeholder="请输入唯一键" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="向量库ID" prop="embeddingStoreId">
          <el-select v-model="form.embeddingStoreId" placeholder="请选择向量库ID">
            <el-option
              v-for="store in embeddingStores"
              :key="store.id"
              :label="store.name"
              :value="store.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="向量模型ID" prop="embeddingModelId">
          <el-select v-model="form.embeddingModelId" placeholder="请选择向量模型ID">
            <el-option
              v-for="model in embeddingModels"
              :key="model.id"
              :label="model.name"
              :value="model.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="descr">
          <el-input v-model="form.descr" type="textarea" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑知识库对话框 -->
    <el-dialog
      :title="'编辑知识库 ' + (form.name || '')"
      v-model="dialogVisibleEdit"
      width="90%"
    >
      <EditKnowledge :knowledge-id="selectedKnowledgeId" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { request } from '../../composables/useCommon'
import { useRouter } from 'vue-router'
import EditKnowledge from './EditKnowledge.vue'

const router = useRouter()

// 表格数据
const tableData = ref([])

// 表格 loading 状态
const loading = ref(false)

// 获取表格数据
const getTableData = async () => {
  try {
    loading.value = true
    const res = await request('ragKnowledge/', 'get', {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      name: searchQuery.value
    })
    tableData.value = res.records
    total.value = res.total
  } catch (err) {
    ElMessage.error('获取知识库列表失败')
  } finally {
    loading.value = false
  }
}

// 新增知识库
const addKnowledge = async (knowledgeData) => {
  try {
    await request('ragKnowledge/', 'post', knowledgeData)
    ElMessage.success('知识库添加成功')
    getTableData()
  } catch (err) {
    ElMessage.error('添加知识库失败')
  }
}

// 修改知识库
const updateKnowledge = async (knowledgeData) => {
  try {
    await request('ragKnowledge/', 'put', knowledgeData)
    ElMessage.success('知识库更新成功')
    getTableData()
  } catch (err) {
    ElMessage.error('更新知识库失败')
  }
}

// 删除知识库
const deleteKnowledge = async (knowledgeId) => {
  try {
    await request(`ragKnowledge/${knowledgeId}`, 'delete')
    ElMessage.success('知识库删除成功')
    getTableData()
  } catch (err) {
    ElMessage.error('删除知识库失败')
  }
}

// 搜索
const searchQuery = ref('')
const handleSearch = () => {
  currentPage.value = 1
  getTableData()
}

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加知识库')
const formRef = ref(null)

// 表单数据
const form = reactive({
  id: '',
  code: '',
  name: '',
  embeddingStoreId: null,
  embeddingModelId: null,
  descr: ''
})

// 表单验证规则
const rules = {
  code: [{ required: true, message: '请输入唯一键', trigger: 'blur' }],
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  embeddingStoreId: [{ required: true, message: '请输入向量库ID', trigger: 'blur' }],
  embeddingModelId: [{ required: true, message: '请输入向量模型ID', trigger: 'blur' }]
}

// 处理添加知识库
const handleAdd = () => {
  dialogTitle.value = '添加知识库'
  Object.keys(form).forEach(key => (form[key] = ''))
  dialogVisible.value = true
}

// 处理编辑知识库
const handleEdit = (row) => {
  selectedKnowledgeId.value = row.id
  dialogVisibleEdit.value = true
}

// 处理删除知识库
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认要删除该知识库吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await deleteKnowledge(row.id)
    } catch (err) {
      ElMessage.error('删除失败')
    }
  })
}

// 处理表单提交
const handleSubmit = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      if (form.id) {
        updateKnowledge(form)
      } else {
        addKnowledge(form)
      }
      dialogVisible.value = false
    }
  })
}

// 编辑对话框相关
const dialogVisibleEdit = ref(false)
const selectedKnowledgeId = ref(null)

// 获取向量库和向量模型数据
const embeddingStores = ref([])
const embeddingModels = ref([])

const fetchEmbeddingStores = async () => {
  try {
    const res = await request('ragEmbeddingStore/', 'get', {
      pageNo: 1,
      pageSize: 10000
    })
    embeddingStores.value = res.data.records
  } catch (err) {
    ElMessage.error('获取向量库失败')
  }
}

const fetchEmbeddingModels = async () => {
  try {
    const res = await request('ragModel/', 'get', {
      pageNo: 1,
      pageSize: 1000,
      type: 'EMBEDDING'
    })
    embeddingModels.value = res.data.records
  } catch (err) {
    ElMessage.error('获取向量模型失败')
  }
}

// 在组件加载时获取数据
onMounted(() => {
  fetchEmbeddingStores()
  fetchEmbeddingModels()
})

// 获取表格数据
getTableData()
</script>

<style scoped>
.knowledge-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

</style>
